package com.gmail.hongyz.myfuse.dataengine;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonResponseImpl implements JsonResponse {

	private JSONObject json = new JSONObject();
	private boolean success = true;
	private String errorMsg;
	private Map<String, Object> parameters = new HashMap<String, Object>();
	private Map<String, Dataset> datasetMap = new HashMap<String, Dataset>();
	
	public JsonResponseImpl() {
//		json.put("parameters", new JSONObject());
	}
	public boolean success() {
		return success;
	}

	public JSONObject toJson() {
		json.put("result", success);
		json.put("errorMsg", errorMsg);
		JSONObject jsParameters = new JSONObject();
		jsParameters.putAll(parameters);
		json.put("parameters", jsParameters);
		JSONArray jsDatasets = new JSONArray();
		for (Iterator<String> iterator = datasetMap.keySet().iterator(); iterator.hasNext();) {
			String datasetId = iterator.next();
			Dataset dataset = datasetMap.get(datasetId);
			JSONObject jsDataset = convertDatasetToJson(dataset);
			jsDataset.put("datasetId", datasetId);
			jsDataset.put("total", dataset.getPageObject().getTotal());
			jsDatasets.add(jsDataset);
		}
		json.put("datasets", jsDatasets);
		return json;
	}
	
	@Override
	public String toString() {
		return toJson().toString();
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}
	
	public void setFail(String message) {
		success = false;
		errorMsg = message;
	}

	public void setParameter(String key, String value) {
//		json.getJSONObject("parameters").put(key, value);
		parameters.put(key, value);
	}
	public void setDataset(String datasetId, Dataset dataset) {
		datasetMap.put(datasetId, dataset);
	}
	private JSONObject convertDatasetToJson(Dataset dataset) {
		JSONArray jsDataset = new JSONArray();
		for (int i = 0; i < dataset.size(); i++) {
			Record record = dataset.getRecord(i);
			JSONObject jsRecord = new JSONObject();
			for (Iterator<String> iterator = record.keys(); iterator.hasNext();) {
				String key = iterator.next();
				jsRecord.put(key, record.get(key));
			}
			jsDataset.add(jsRecord);
		}
		JSONObject jsRecords = new JSONObject();
		jsRecords.put("records", jsDataset);
		return jsRecords;
	}
}
